package com.resou.reader.activity.limitedrecharge;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.resou.reader.R;
import com.resou.reader.api.entry.ActivityRechargePrice;
import com.resou.reader.base.ToolbarActivity;
import com.resou.reader.dialog.DialogManager;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.utils.TimeUtil;
import com.resou.reader.utils.ToastUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;
import java.util.List;
import java.util.concurrent.TimeoutException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 显示 充值活动页
 */
public class LimitedRechargeActivity extends ToolbarActivity<LimitedRechargePresenter> implements LimitedRechargeContract.View {

    public static final String REMAINING_TIME = "remaining_time";
    @BindView(R.id.imageView4)
    ImageView imageView4;

    @BindView(R.id.linearLayout6)
    LinearLayout linearLayout6;

    final long TIME = (long) 3 * 24 * 60 * 60 * 1000;

    @BindView(R.id.tv_hour)
    TextView tvHour;
    @BindView(R.id.tv_minute)
    TextView tvMinute;

    @BindView(R.id.tv_activity_rule)
    TextView tvActivityRule;
    @BindView(R.id.tv_second)
    TextView tvSecond;
    @BindView(R.id.tv_price_1)
    TextView tvPrice1;
    @BindView(R.id.tv_price_2)
    TextView tvPrice2;

    private CountDownTimer mTimer;
    private QMUITipDialog mDialog;

    public static void start(Context context, long remainingTime) {
        Intent starter = new Intent(context, LimitedRechargeActivity.class);
        starter.putExtra(REMAINING_TIME, remainingTime);
        context.startActivity(starter);
    }

//    @Override
//    protected void initStatusBar() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//            getWindow().setStatusBarColor(getColor(R.color.white));
//        }
//        setSupportActionBar(toolbar);
//        ActionBar actionBar = getSupportActionBar();
//        if (actionBar != null) {
//            actionBar.setDisplayShowTitleEnabled(false);
//            actionBar.setDisplayHomeAsUpEnabled(true);
//        }
//    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_limited_time_recharge);
        ButterKnife.bind(this);

        setTitle("限时充值");
        initPresenter();
        initData();
    }

    private void initPresenter() {
        mPresenter = new LimitedRechargePresenter(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
        }
    }

    @Override
    public void initData() {
        long remainingTime = getIntent().getLongExtra(REMAINING_TIME, 0);
        showCountTime(remainingTime);
        mPresenter.loadActivityInfo();
        mPresenter.loadRechargePrice(12);
    }

    @Override
    public void showContent() {

    }

    @Override
    public void showError(Throwable throwable) {
        if (throwable instanceof UnknownHostException
                || throwable instanceof UnknownServiceException
                || throwable instanceof TimeoutException || throwable instanceof ConnectException) {
            ToastUtil.makeShortToast("网络错误，请检查网络状况！");
        } else {
            ToastUtil.makeShortToast("未知错误，请稍后重试");
        }
    }

    @Override
    public void showEmpty() {

    }

    private static final String TAG = "LimitedRecharge-App";

    @Override
    public void showCountTime(long lastTime) {
        /**
         * 服务器返回的是时间戳，是以秒计算的,必须要乘1000
         *
         * Java当中是以毫秒计算的
         * C++当中是以秒计算的
         */
        long l = lastTime * 1000 - System.currentTimeMillis();
        mTimer = new CountDownTimer(l, 1000) {

            //            String day;
            String mHour = "";
            String mMinute = "";
            String mSecond = "";

            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
//                String day = TimeUtil.getDay(millisUntilFinished);
                String hour = TimeUtil.getAllHour(millisUntilFinished);
                String minute = TimeUtil.getStringMinute(millisUntilFinished);
                String second = TimeUtil.getStringSecond(millisUntilFinished);
//                if (!day.equals(this.day)) {
//                    this.day = day;
//                    tvDay.setText(day + "天");
//                }
                if (!mHour.equals(hour)) {
                    mHour = hour;
                    tvHour.setText(hour + "时");
                }
                if (!mMinute.equals(minute)) {
                    mMinute = minute;
                    tvMinute.setText(minute + "分");
                }
                if (!mSecond.equals(second)) {
                    mSecond = second;
                    tvSecond.setText(second + "秒");
                }
            }

            @Override
            public void onFinish() {

            }
        }.start();
    }

    @Override
    public void showNetCountTime(long lastTime) {
        mTimer = new CountDownTimer(lastTime * 1000, 1000) {
            //            String day;
            String mHour = "";
            String mMinute = "";
            String mSecond = "";

            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
//                String day = TimeUtil.getDay(millisUntilFinished);
                String hour = TimeUtil.getAllHour(millisUntilFinished);
                String minute = TimeUtil.getStringMinute(millisUntilFinished);
                String second = TimeUtil.getStringSecond(millisUntilFinished);
//                if (!day.equals(this.day)) {
//                    this.day = day;
//                    tvDay.setText(day + "天");
//                }
                if (!mHour.equals(hour)) {
                    mHour = hour;
                    tvHour.setText(hour + "时");
                }
                if (!mMinute.equals(minute)) {
                    mMinute = minute;
                    tvMinute.setText(minute + "分");
                }
                if (!mSecond.equals(second)) {
                    mSecond = second;
                    tvSecond.setText(second + "秒");
                }
            }

            @Override
            public void onFinish() {

            }
        }.start();
    }

    private Method noteStateNotSavedMethod;
    private Object fragmentMgr;
    private String[] activityClassName = {"Activity", "FragmentActivity"};

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //解决cannot perform the action after onSaveInstanceState
        invokeFragmentManagerNoteStateNotSaved();
    }

    private void invokeFragmentManagerNoteStateNotSaved() {
        //java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            return;
        }
        try {
            if (noteStateNotSavedMethod != null && fragmentMgr != null) {
                noteStateNotSavedMethod.invoke(fragmentMgr);
                return;
            }
            Class cls = getClass();
            do {
                cls = cls.getSuperclass();
            } while (!(activityClassName[0].equals(cls.getSimpleName())
                    || activityClassName[1].equals(cls.getSimpleName())));

            Field fragmentMgrField = prepareField(cls, "mFragments");
            if (fragmentMgrField != null) {
                fragmentMgr = fragmentMgrField.get(this);
                noteStateNotSavedMethod = getDeclaredMethod(fragmentMgr, "noteStateNotSaved");
                if (noteStateNotSavedMethod != null) {
                    noteStateNotSavedMethod.invoke(fragmentMgr);
                }
            }

        } catch (Exception ignored) {
        }
    }

    private Field prepareField(Class<?> c, String fieldName) throws NoSuchFieldException {
        while (c != null) {
            try {
                Field f = c.getDeclaredField(fieldName);
                f.setAccessible(true);
                return f;
            } finally {
                c = c.getSuperclass();
            }
        }
        throw new NoSuchFieldException();
    }

    private Method getDeclaredMethod(Object object, String methodName, Class<?>... parameterTypes) {
        Method method = null;
        for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                method = clazz.getDeclaredMethod(methodName, parameterTypes);
                return method;
            } catch (Exception ignored) {
            }
        }
        return null;
    }

    /**
     * 显示签到规则
     *
     * @param activityRules
     */
    @Override
    public void showActivityInfo(String activityRules) {
        tvActivityRule.setText(activityRules);
    }

    @Override
    public void showPayDialog(String price) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        DialogManager.showThreeDaysRechargeDialog(getSupportFragmentManager(), price);
    }

    @Override
    public void showAlreadyPay(String msg) {
//        ToastUtil.makeLongToast(msg);
        if (mDialog != null) {
            mDialog.dismiss();
        }
        QMUITipDialog dialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                .setTipWord(msg)
                .create();
        dialog.show();

        new Handler().postDelayed(dialog::dismiss, 1000);
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }

    @Override
    public void showProgress(String msg) {
        mDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord(msg)
                .create();
        mDialog.show();
    }

    /**
     * 显示价格
     *
     * @param data
     */
    @Override
    public void setPrices(List<ActivityRechargePrice> data) {
        tvPrice1.setText("充" + data.get(0).getPrice() + "元得" + +data.get(0).getActivityPrice() + "00热币（推荐）");
        tvPrice1.setOnClickListener((v -> {
            if (!UserInstance.isLogin()) {
                DialogManager.showLoginDialog(getSupportFragmentManager());
            } else {
                mPresenter.checkUserIsPayInRechargeActivity(String.valueOf(data.get(0).getPrice()));
            }
        }));
        tvPrice2.setText("充" + data.get(1).getPrice() + "元得" + +data.get(1).getActivityPrice() + "00热币");
        tvPrice2.setOnClickListener((v -> {
            if (!UserInstance.isLogin()) {
                DialogManager.showLoginDialog(getSupportFragmentManager());
            } else {
                mPresenter.checkUserIsPayInRechargeActivity(String.valueOf(data.get(1).getPrice()));
            }
        }));
    }
}
